<template>
  <div class="com-input-container textInput" :class="{ hasUnit: unit }" :data-unit="unit">
    <span class="title" :class="{ required }" v-if="title">{{ title.replace(/^(.)(.)$/, '$1　　$2') }}：</span>
    <input v-model.trim="bindValue"
      @input="onInput"
      @focus="focusInput"
      :type="type"
      :placeholder="placeholder"
      :readonly="readonly"
    >
    <slot name="right"></slot>
  </div>
</template>

<script>
export default {
  props: ['title', 'required', 'value', 'unit', 'placeholder', 'type', 'readonly', 'max'],

  data (){
    return {
      bindValue: this.value
    }
  },

  watch: {
    value (val){
      this.bindValue = val
    }
  },

  methods: {
    focusInput (e){
      setTimeout(() => e.target.scrollIntoView(), 200)
    },

    onInput (e){
      var value = this.max ? e.target.value.substring(0, this.max) : e.target.value

      // 类型为数字时禁止输入非数字字符
      if(this.type === 'number'){
        value = value.replace(/[^\d\.]/g, '')
      }

      value = value.trim()
      this.bindValue = value
      this.$emit('input', value)
    }
  }
}
</script>

<style lang="less" scoped>
.com-input-container{
  height: 25px;
  margin: 15px 0;

  &.hasUnit{
    position: relative;

    &::before{
      content: attr(data-unit);
      position: absolute;
      top: calc(~'50% - 1px');
      right: 0;
      transform: translateY(-50%);
      color: @subtext;
    }
  }

  .title.required{
    position: relative;

    &::before{
      content: '*';
      display: inline;
      color: @danger;
      position: absolute;
      top: 50%;
      left: -10px;
      transform: translateY(-50%);
    }
  }

  > input{
    border-bottom: 1px @subtext solid;
    transition: 0.3s border linear;
    box-sizing: initial;

    &:focus{
      border-color: @theme;
    }
  }
}
</style>
